#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-

import sys
from future_builtins import *

import cgi
import getpass
import json
import re
import time
import urllib

import httplib2

if len(sys.argv) == 1:
    username = raw_input('Username: ')
    password = getpass.getpass()
elif len(sys.argv) == 2:
    username = sys.argv[1]
    password = getpass.getpass()
elif len(sys.argv) == 3:
    username = sys.argv[1]
    password = sys.argv[2]
else:
    print >> sys.stderr, 'Usage: findmyiphone.py [username] [password]'
    sys.exit(1)
http = httplib2.Http()
response, content = http.request('https://auth.me.com/authenticate', 'POST', body=urllib.urlencode({'service': 'account', 'ssoNamespace': 'primary-me', 'returnURL': 'https://secure.me.com/account/#findmyiphone'.encode('base64'), 'anchor': 'findmyiphone', 'formID': 'loginForm', 'username': username, 'password': password}), headers={'Content-Type': 'application/x-www-form-urlencoded'})
if 'set-cookie' not in response:
    print >> sys.stderr, 'Incorrect member name or password.'
    sys.exit(1)
cookie1 = response['set-cookie']
response, content = http.request('https://secure.me.com/wo/WebObjects/Account2.woa?lang=en&anchor=findmyiphone', 'GET', headers={'Cookie': cookie1, 'X-Mobileme-Version': '1.0'})
cookie2 = response['set-cookie']
lsc, = re.search('isc-secure\\.me\\.com=(.*?);', response['set-cookie']).groups()
response, content = http.request('https://secure.me.com/wo/WebObjects/DeviceMgmt.woa', 'POST', headers={'Cookie': cookie1 + ', ' + cookie2, 'X-Mobileme-Version': '1.0', 'X-Mobileme-Isc': lsc})
if json.loads(content)['status'] == 0:
    print >> sys.stderr, 'Find My iPhone is unavailable.'
    sys.exit(1)
id, os_version = re.search('new Device\\([0-9]+, \'(.*?)\', \'.*?\', \'.*?\', \'(.*?)\', \'(?:false|true)\', \'(?:false|true)\'\\)', content).groups()
response, content = http.request('https://secure.me.com/wo/WebObjects/DeviceMgmt.woa/wa/LocateAction/locateStatus', 'POST', body='postBody=' + json.dumps({'deviceId': id, 'deviceOsVersion': os_version}), headers={'Cookie': cookie1 + ', ' + cookie2, 'X-Mobileme-Version': '1.0', 'X-Mobileme-Isc': lsc})
for key, value in sorted(json.loads(content).items()):
    print '{key:22}  {value}'.format(key=key, value=value)
